Imports System.Web.Security
Imports MIMS.WRS.Business
Imports MIMS.WRS.Data
Imports MIMS.WRS.Entities


Public Class UserSignIn
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents lblErr As System.Web.UI.WebControls.Label
    Protected WithEvents txtUsername As System.Web.UI.WebControls.TextBox
    Protected WithEvents RequiredFieldValidator1 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtPassword As System.Web.UI.WebControls.TextBox
    Protected WithEvents btnOK As System.Web.UI.WebControls.Button
    Protected WithEvents btnCancel As System.Web.UI.WebControls.Button
    Protected WithEvents Label1 As System.Web.UI.WebControls.Label
    Protected WithEvents rowAlreadyLogin As System.Web.UI.HtmlControls.HtmlTableRow
    Protected WithEvents rowLogin As System.Web.UI.HtmlControls.HtmlTableRow
    Protected WithEvents lnkForgotYourPassword As System.Web.UI.WebControls.LinkButton
    Protected WithEvents lblEmail As System.Web.UI.WebControls.Label
    Protected WithEvents linkSignInOther As System.Web.UI.WebControls.LinkButton

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        If (Not IsPostBack) Then
            'Dim userID As Integer
            'Dim user As New ShoppingUser
            'user.Email = "test@yahoo.com"
            'user.Password = Utilities.HashPassword("qwert")
            'userID = ShoppingListService.CreateShoppingUser(user)
            If (IsFromSignInOthers) Then
                rowAlreadyLogin.Visible = False
                rowLogin.Visible = Not rowAlreadyLogin.Visible
            Else
                rowAlreadyLogin.Visible = (ShoppingConext.ShopingUserId <> 0)
                rowLogin.Visible = Not rowAlreadyLogin.Visible
            End If
        End If
    End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        Try
            Dim userID As Integer = ShoppingListService.Login(txtUsername.Text.Trim(), Utilities.HashPassword(txtPassword.Text))
            If (userID > 0) Then
                ShoppingConext.ShopingUserEmail = txtUsername.Text.Trim()
                ShoppingConext.ShopingUserId = userID
                GetShoppingListFromDB(userID)
            Else
                lblErr.Text = "Invalid email or password"
            End If
        Catch ex As Exception
            lblErr.Text = ex.Message
        End Try
    End Sub

    ' To be removed
    Private Sub btnOK_Click_Old(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            Dim userID As Integer = ShoppingListService.Login(txtUsername.Text.Trim(), Utilities.HashPassword(txtPassword.Text))
            If (userID <> 0) Then
                Dim strScript As String = "<script language='javascript'>windowClose();</script>"
                GetShoppingListFromDB(userID)

                If (Convert.ToInt32(Session(Constant.SS_CONPOINT_ID)) = Convert.ToInt32(Session(Constant.SS_SELECTED_CONPOINT_ID)) AndAlso Convert.ToInt32(Session(Constant.SS_CONPOINT_ID)) > 0) OrElse _
                       (Convert.ToInt32(Session(Constant.SS_CONPOINT_ID)) = 0) OrElse (Convert.ToInt32(Session(Constant.SS_SELECTED_CONPOINT_ID)) = 0) Then
                    If (Not IsFromAddToCart) Then
                        strScript = "<script language='javascript'>windowCloseAndRefresh1();</script>"   'refresh
                    End If
                    If ((Convert.ToInt32(Session(Constant.SS_CONPOINT_ID)) = 0)) Then
                        Session(Constant.SS_CONPOINT_ID) = Session(Constant.SS_SELECTED_CONPOINT_ID)
                    End If
                    If ((Convert.ToInt32(Session(Constant.SS_SELECTED_CONPOINT_ID)) = 0)) Then
                        Session(Constant.SS_SELECTED_CONPOINT_ID) = Session(Constant.SS_CONPOINT_ID)
                    End If
                    ShoppingConext.ShopingUserEmail = txtUsername.Text.Trim()
                    ShoppingConext.ShopingUserId = userID
                    Page.RegisterStartupScript("windowClose", strScript)
                Else
                    Dim selectedConPointID As Int32 = Convert.ToInt32(Session(Constant.SS_SELECTED_CONPOINT_ID))
                    If (Not Session(Constant.SS_CONPOINT_ID) Is Nothing AndAlso Convert.ToInt32(Session(Constant.SS_CONPOINT_ID)) > 0 AndAlso _
                            Convert.ToInt32(Session(Constant.SS_CONPOINT_ID)) <> selectedConPointID AndAlso selectedConPointID > 0) Then
                        Response.Redirect(String.Format("ConfirmToOverwriteShopplingList.aspx?CurConPointID={0}&ConPointID={1}&userid={2}&useremail={3}", Session(Constant.SS_CONPOINT_ID), Session(Constant.SS_SELECTED_CONPOINT_ID), userID, txtUsername.Text.Trim()))
                    End If
                End If
            Else
                lblErr.Text = "Invalid email or password"
            End If
        Catch ex As Exception
            lblErr.Text = ex.Message
        End Try
    End Sub

    Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
        btnCancel.Attributes.Add("onclick", "javascript:window.close();return false;")
    End Sub

    Private ReadOnly Property IsFromAddToCart() As Boolean
        Get

            If (Not Request.Item("from") Is Nothing AndAlso Request.Item("from").ToString() = "addToCart") Then
                Return True
            End If
            Return False
        End Get
    End Property

    Private ReadOnly Property IsFromSignInOthers() As Boolean
        Get

            If (Not Request.Item("from") Is Nothing AndAlso Request.Item("from").ToString() = "SignInOther") Then
                Return True
            End If
            Return False
        End Get
    End Property

    Private Sub GetShoppingListFromDB(ByVal shopingUserId As Integer)
        'If first time user click "Click here" link (currently no have any selection) 
        ' then check to see if existing saved list:
        ' + existing for 1 con point: display this list 
        ' + existing for more than 1 con point: show Con Point selection screen for user select.
        'If user select some items then click on "Click here" then reload the existing saved list(if have) merger with current selection list

        If (shopingUserId > 0) Then
            Dim oCollection As New Collection
            If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing AndAlso Not IsFromSignInOthers) Then
                oCollection = DirectCast(Session(Constant.SS_SHOPPING_LIST), Collection)
            End If

            If (IsFromSignInOthers) Then
                Session(Constant.SS_SHOPPING_LIST) = Nothing
                Session(Constant.SS_CONPOINT_ID) = Nothing
            End If

            Dim shoppingOrderCol As ShoppingOrderCollection = ShoppingListService.GetShoppingOrderByShoppingUserId(shopingUserId)
            Dim shoppingOrderItem As New ShoppingOrder
            Dim bExisted As Boolean = False
            Dim conPointIDList As New ListItemCollection
            Dim conPointString As String = ""
            If (Not shoppingOrderCol Is Nothing AndAlso shoppingOrderCol.Count > 0) Then
                For Each item As ShoppingOrder In shoppingOrderCol
                    If (ShoppingConext.ShopingSelectedConsolidation = item.ConPointID) Then
                        shoppingOrderItem = item
                        bExisted = True
                    End If
                    If (conPointIDList.FindByValue(item.ConPointID.ToString()) Is Nothing) Then
                        conPointIDList.Add(New ListItem(item.ConPointID.ToString(), item.ConPointID.ToString()))
                        conPointString = conPointString & item.ConPointID.ToString() & ";"
                    End If
                Next

            End If
            'There is a selection list currently.
            If (ShoppingConext.ShopingSelectedConsolidation > 0) Then
                If (bExisted) Then 'Load a existing saved list & current selection if have
                    Dim previousShoppingList As Collection = LoadShoppingToCurrentSelection(shopingUserId, ShoppingConext.ShopingSelectedConsolidation, shoppingOrderItem)
                    If (Not oCollection Is Nothing AndAlso oCollection.Count > 0) Then
                        For i As Integer = 1 To oCollection.Count
                            previousShoppingList.Add(DirectCast(oCollection(i), ShoppingItem))
                        Next
                    End If
                    Session(Constant.SS_SHOPPING_LIST) = previousShoppingList
                Else
                    ' do nothing if there is a selection and no have saved list for current Con Point ( mean just show what user select)
                End If
                ClosePageAndRefresh()
            Else
                ' There is no selection currently
                If (conPointIDList.Count > 0) Then
                    If (conPointIDList.Count = 1) Then ' load this saved list
                        Dim conPointId As Integer = 0
                        Try
                            conPointId = Convert.ToInt32(conPointIDList(0).Value)
                        Catch ex As Exception
                        End Try
                        shoppingOrderItem = shoppingOrderCol(0)
                        Dim previousShoppingList As Collection = LoadShoppingToCurrentSelection(shopingUserId, conPointId, shoppingOrderItem)
                        Session(Constant.SS_SHOPPING_LIST) = previousShoppingList
                        ShoppingConext.ShopingSelectedConsolidation = conPointId
                        ClosePageAndRefresh()
                    Else ' there are more than 1 con point that is for saved list 

                        ' Redirect to screen that allow user select appropriate shopping list by con point.
                        Response.Redirect(String.Format("ConPointSelection.aspx?ConPointIDString={0}", conPointString))
                    End If
                End If
            End If
        End If
    End Sub

    Function LoadShoppingToCurrentSelection(ByVal shopingUserId As Integer, ByVal selectedConPoint As Integer, ByVal shoppingOrderItem As ShoppingOrder) As Collection
        If (Not shoppingOrderItem Is Nothing) Then
            Session("txtQty20Cont") = shoppingOrderItem.Qty20
            Session("txtQty40Cont") = shoppingOrderItem.Qty40
            Session("txtQty40HiCube") = shoppingOrderItem.Qty40HC

            Session("txtOrderNo") = shoppingOrderItem.OrderNo
            Session("txtHalfPallet") = shoppingOrderItem.HalfPalletSpaces
            Session("txtExistingOrderVolume") = shoppingOrderItem.FilledVolume

            Session("rdPartOrder") = shoppingOrderItem.OrderType

            Session("ddlCountry") = shoppingOrderItem.DestinationCountryId
            ShoppingConext.ShoppingOrderId = shoppingOrderItem.ShoppingOrderId
        End If

        Dim shoppingItemsList As ShoppingListCollection = ShoppingListService.GetShoppingListByShoppingUserIdAndConPoint(shopingUserId, selectedConPoint)
        Dim previousShoppingList As New Collection
        If (Not shoppingItemsList Is Nothing AndAlso shoppingItemsList.Count > 0) Then
            Dim item As New shoppingItem
            For Each shoppingItem As ShoppingList In shoppingItemsList
                item = New shoppingItem
                With item
                    .ItemNo = shoppingItem.IDSSort
                    .ProductCode = shoppingItem.ProductCode
                    .Description = shoppingItem.Description
                    .Quantity = shoppingItem.Qty
                    .UnitDesc = shoppingItem.UnitSetting
                    Try
                        .UnitSettingID = shoppingItem.UnitSettingID
                    Catch ex As Exception
                    End Try

                    .UnitPrice = shoppingItem.UnitPrice
                    .Total = shoppingItem.TotalPrice
                    .UnitWeight = Convert.ToDecimal(shoppingItem.UnitWeight)
                    .Priority = shoppingItem.PriorityIndex
                    .BulkOrderId = shoppingItem.BulkOrderId
                    .TerritoryID = shoppingItem.TerritoryID
                    .MinQtyVolume = Convert.ToDecimal(shoppingItem.MinQtyVolume)
                    .CountryId = selectedConPoint
                End With
                previousShoppingList.Add(item)
            Next
        End If

        Return previousShoppingList
    End Function

    Private Sub ClosePageAndRefresh()
        Dim strScript As String = "<script language='javascript'>windowClose();</script>"
        If (Not IsFromAddToCart) Then
            strScript = "<script language='javascript'>windowCloseAndRefresh1();</script>"   'refresh
        End If
        Page.RegisterStartupScript("windowClose", strScript)
    End Sub

    Private Sub lnkForgotYourPassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkForgotYourPassword.Click
        Response.Redirect("ForgotYourPassword.aspx")
    End Sub

End Class
